<?php
namespace app\admin\controller;
use think\Controller;
use think\Session;
use think\Db;
class Base extends Controller
{
    /**
     * 构造函数
     */
    public function _initialize()
    {
        //检查是否登录

        if(!Session::has('admin')) {
            $this->redirect('admin/login/login');
        }

        //检查权限
        $result = $this->checkAuth();
        if ($result != 'next') {
            $arr = ['data'=>'','code'=>1,'message'=>'无访问权限'];
            echo json_encode($arr,JSON_UNESCAPED_UNICODE);die;
        }
    }

    /**
     * 检查权限
     */
    protected function checkAuth()
    {
        $controller = $this->request->controller();
        $action = $this->request->action();
        $url = $controller.'/'.$action;
        $url = url($url);
        $node = $this->getAuthNode('all');
        foreach ($node as $k => $val) {
            if (!empty($val['name'])) {
                $tempArr[] = url($val['name']);
            }
        }

        //添加必须的默认权限
        $tempArr[] = url('index/index'); //框架首页
        $tempArr[] = url('index/welcome'); //欢迎页

        if (!in_array($url,$tempArr)) {
            return 403;
        } else {
            return 'next';
        }
    }

    /**
     * 根据用户权限取节点菜单
     */
    protected function getAuthNode($isshow = 'all')
    {
        $admin = Session::get('admin');
        $user = Db::name('manage')
            ->alias('m')
            ->join('__GROUP__ g','m.manage_id = g.group_id','LEFT')
            ->where($admin['manage_id'])->find();
        $auth = $user['auth'];
        if ($isshow == 'all') {
            $map['node_id'] = ['in',$auth];
        } else {
            $map['node_id'] = ['in',$auth];
            $map['isshow'] = 0;
        }
        $node = Db::name('node')->where($map)->order('sort,name asc')->select();
        return $node;
    }


    /**
     * 按规则排序节点
     * @param $node
     * @return array
     */
    protected function nodeSort($node)
    {
        $nodes = array();
        //先找出顶级菜单
        foreach ($node as $k => $val) {
            if($val['pid'] == 0) {
                $nodes[$k] = $val;
            }
        }
        //通过顶级菜单找到下属的子菜单
        foreach ($nodes as $k => $val) {
            foreach ($node as $key => $value) {
                if($value['pid'] == $val['node_id']) {
                    $value['name'] = url($value['name']);
                    $nodes[$k]['children'][] = $value;
                }
            }
        }
        return $nodes;
    }
}
